package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.Role;
import com.conversationboard.model.User;
import com.conversationboard.model.exceptions.UserDoesNotExistException;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AddUserToPrivateBoardControllerServlet", urlPatterns = "/AddUserToPrivateBoardControllerServlet")
public class AddUserToPrivateBoardControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -8154777920669060145L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		int boardId = Integer.parseInt(request.getParameter("boardid"));
		String userToBeAddedLoginId = request.getParameter("email");

		try {

			Board board = Boards.getBoard(boardId);
			String loginId = request.getUserPrincipal().getName();
			User user = User.get(loginId);

			/* Check authorisation */

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, loginId)) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			if (!(user.isMemberOfBoard(boardId) && user.canAddUsersToBoard(board))) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
				dispatcher.forward(request, response);
				return;
			}

			User userToBeAdded = User.get(userToBeAddedLoginId);

			if (userToBeAdded.getRole() == Role.Anonymous) {
				request.setAttribute("message", "User: " + userToBeAddedLoginId + " does not exist in the database.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			userToBeAdded.allowAccessToBoard(boardId);

			request.setAttribute("message", "User has been successfully added to private board.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (EncryptionException e) {
			throw new ServletException(e);
		} catch (UserDoesNotExistException e) {
			request.setAttribute("message", "User: " + userToBeAddedLoginId + " does not exist in the database.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);
			return;
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
